import React, { Component, useEffect, useState } from "react";
import course_logo from "../../assets/courselogo_transparent.png";
import "./css/explore.css";
import {
  CaretRightOutlined,
  QuestionOutlined,
  RightOutlined,
  SearchOutlined,
  PlusOutlined,
} from "@ant-design/icons";
import {
  Radio,
  Button,
  Collapse,
  Checkbox,
  Col,
  Drawer,
  Row,
  ConfigProvider,
  List,
  Pagination,
} from "antd";
import SearchResults from "./SearchResults";
import { Axios } from "../../utils";

const onChange = (checkedValues) => {
  console.log("checked = ", checkedValues);
};

const { Panel } = Collapse;

//储存当前查找的技术列表
var TechList = [];

//储存所有查到的课程资料
var AllResource = [];

class Explore extends Component {
  constructor(props) {
    super(props);
    this.state = {
      SearchContent: "",
      SearchType: "course",
      SearchPage: 1,
      TechType: "",
      ResourceType: "",
      open: false,
      childrenDrawer: false,
      CourseList: [
        {
          key: 1,
          name: "course1",
        },
        {
          key: 2,
          name: "course2",
        },
      ],
      ResourceData: [
        {
          key: 0,
          title: "Rcing car sprays burning fuel into crowd.",
          img: "http://img.zhux2.com/editor1505610497320414.jpg",
          discription: "This is discription of the content.",
          course_url: "www.baidu.com",
        },
        // {
        //   title: "Japanese princess to wed commoner.",
        //   img: "./assets/texture-7515225.jpg",
        //   discription: "This is discription of the content.",
        //   course_url:"www.baidu.com"
        // },
        // {
        //   title: "Australian walks 100km after outback crash.",
        //   img: "./assets/texture-7515225.jpg",
        //   discription: "This is discription of the content.",
        //   course_url:"www.baidu.com"
        // },
        // {
        //   title: "Man charged over missing wedding girl.",
        //   img: "./assets/texture-7515225.jpg",
        //   discription: "This is discription of the content.",
        //   course_url:"www.baidu.com"
        // },
        // {
        //   title: "Los Angeles battles huge wildfires.",
        //   img: "./assets/texture-7515225.jpg",
        //   discription: "This is discription of the content.",
        //   course_url:"www.baidu.com"
        // },
      ],
      AllTechList: [],
    };

    this.handleTypeChange = this.handleTypeChange.bind(this);
    this.handlePageChange = this.handlePageChange.bind(this);
    this.handleContentChange = this.handleContentChange.bind(this);
    this.SearchResources = this.SearchResources.bind(this);
    this.handleTechChange = this.handleTechChange.bind(this);
    this.handleResourceChange = this.handleResourceChange.bind(this);
    this.handleResourceData = this.handleResourceData.bind(this);
    Axios({
      method: "get",
      url: "/course/searchName",
      params: { course_name: "" },
    }).then(
      (response) => {
        const res = response.data;
        AllResource = res.map((item) => {
          return {
            course_name: item.course_name,
            key: item.course_id,
            course_description: item.course_description,
            course_type: item.course_type,
            course_url: item.course_url,
            course_id: item.course_id,
            tech_id: item.tech_id,
            tech_name: item.tech_name,
          };
        });
        // this.state.ResourceData = res.map(item=>{
        //   return {title:item.course_name, key: item.course_id,discription:item.course_description, type:item.course_type,url:item.course_url}
        // })
        this.handleResourceData(res);

        this.handleResourceChange(["网课", "文档", "仓库", "实用工具", "博客"]);
      },
      (error) => {}
    );
  }

  componentDidMount() {
    Axios({ method: "get", url: "/tech/techList" }).then((response) => {
      this.setState({
        AllTechList: response.data.map((item) => {
          return { ...item, key: item.tech_id };
        }),
      });
    });
  }

  shouldComponentUpdate(newPro, newState) {
    return true;
  }

  TechListCol = TechList.map((tech) => (
    <Col span={12} align="start">
      <Checkbox value={tech.name}>
        <p>{tech.name}</p>
      </Checkbox>
    </Col>
  ));

  handleResourceData = (NewResourceData) => {
    this.setState({
      ResourceData: NewResourceData.map((item) => {
        return {
          course_name: item.course_name,
          key: item.course_id,
          course_description: item.course_description,
          course_type: item.course_type,
          course_url: item.course_url,
          course_id: item.course_id,
          tech_id: item.tech_id,
          tech_name: item.tech_name,
        };
      }),
    });
  };

  SearchResources = (
    SearchType,
    SearchContent,
    SearchPage,
    TechType,
    ResourceType
  ) => {
    // console.log(
    //   "search " +
    //   SearchType +
    //   ": " +
    //   SearchContent +
    //   " at page " +
    //   SearchPage +
    //   " for " +
    //   TechType +
    //   ResourceType
    // );

    if (SearchType === "course") {
      Axios({
        method: "get",
        url: "/course/searchName",
        params: {
          course_name: SearchContent,
        },
      }).then(
        (response) => {
          const res = response.data;
          AllResource = res.map((item) => {
            return {
              course_name: item.course_name,
              key: item.course_id,
              course_description: item.course_description,
              course_type: item.course_type,
              course_url: item.course_url,
              course_id: item.course_id,
              tech_id: item.tech_id,
              tech_name: item.tech_name,
            };
          });
          // this.state.ResourceData = res.map(item=>{
          //   return {title:item.course_name, key: item.course_id,discription:item.course_description, type:item.course_type,url:item.course_url}
          // })
          this.handleResourceData(res);

          this.handleResourceChange([
            "网课",
            "文档",
            "仓库",
            "实用工具",
            "博客",
          ]);
        },
        (error) => {}
      );
    } else {
      Axios({
        method: "get",
        url: "/course/searchTechName",
        params: {
          tech_name: SearchContent,
        },
      }).then(
        (response) => {
          const res = response.data;
          AllResource = res.map((item) => {
            return {
              course_name: item.course_name,
              key: item.course_id,
              course_description: item.course_description,
              course_type: item.course_type,
              course_url: item.course_url,
              course_id: item.course_id,
              tech_id: item.tech_id,
              tech_name: item.tech_name,
            };
          });
          // this.state.ResourceData = res.map(item=>{
          //   return {title:item.course_name, key: item.course_id,discription:item.course_description, type:item.course_type,url:item.course_url}
          // })
          this.handleResourceData(res);

          this.handleResourceChange([
            "网课",
            "文档",
            "仓库",
            "实用工具",
            "博客",
          ]);
        },
        (error) => {}
      );
    }
  };

  handleTypeChange = (event) => {
    this.setState({ SearchType: event.target.value });
  };

  handlePageChange = (event) => {
    this.setState({ SearchPage: event });
  };

  handleContentChange = (event) => {
    this.setState({ SearchContent: event.target.value });
  };

  handleTechChange = (event) => {
    this.setState({ TechType: event });
    //技术类型选择框选择
    var new_tech_list = [];
    var temp_resource_list = AllResource;
    for (var j = 0; j < this.state.ResourceType.length; j++) {
      temp_resource_list.filter(
        (item) => item.course_type === this.state.ResourceType[j]
      );
    }
    for (var i = 0; i < event.length; i++) {
      var temp = temp_resource_list.filter(
        (item) => item.tech_name === event[i]
      );
      new_tech_list.push.apply(new_tech_list, temp);
    }
    this.handleResourceData(new_tech_list);
  };

  handleResourceChange = (event) => {
    this.setState({ ResourceType: event });
    //资源类型选择框选择
    var new_resource_list = [];
    for (var i = 0; i < event.length; i++) {
      var temp = AllResource.filter((item) => item.course_type === event[i]);
      new_resource_list.push.apply(new_resource_list, temp);
    }
    this.handleResourceData(new_resource_list);

    //资源类型选择框改变后改变技术类型
    var new_tech_list = [];

    let techStringToTechId = new Map();
    for (let i = 0; i < new_resource_list.length; i++) {
      if (techStringToTechId.has(new_resource_list[i].tech_name)) {
      } else {
        techStringToTechId.set(
          new_resource_list[i].tech_name,
          new_resource_list[i].tech_id
        );
      }
    }

    for (let [key, value] of techStringToTechId) {
      new_tech_list.push({
        tech_name: key,
        tech_id: value,
      });
    }

    TechList = new_tech_list.map((item) => {
      return { name: item.tech_name, key: item.tech_id };
    });

    const trueValue = true;

    this.TechListCol = TechList.map((tech) => (
      <Col span={24} align="start">
        <Checkbox value={tech.name} checked={trueValue}>
          <p>
            <font size="2">{tech.name}</font>
          </p>
        </Checkbox>
      </Col>
    ));
  };

  showDrawer = () => {
    this.setState({ open: true });
  };

  onClose = () => {
    this.setState({ open: false });
  };

  showChildrenDrawer = (tech_name) => {
    this.setState({ childrenDrawer: true });
    //console.log(tech_name)
  };

  onChildrenDrawerClose = () => {
    this.setState({ childrenDrawer: false });
  };

  chooseTech = (tech) => {
    this.setState({ SearchType: "tech", SearchContent: tech });
    this.SearchResources("tech", tech, 1, "", "");
  };

  chooseCourse = (course) => {
    this.setState({ SearchType: "course", SearchContent: course });
    this.SearchResources("course", course, 1, "", "");
  };

  addToFavorite = (resource) => {
    console.log("Add to myLikes.")
    console.log(resource.course_name)
    var list = JSON.parse(JSON.parse(JSON.stringify(localStorage.getItem("myLikes"))));
    if (list == null) {
      const date = new Date();
      var newList = [{
        course_url: resource.course_url,
        course_name: resource.course_name,
        date: `${date.getFullYear()}-${date.getMonth()}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`,
      },];
      localStorage.setItem("myLikes", JSON.stringify(newList));
    } else {
      const date = new Date();
      list.unshift({
        course_url: resource.course_url,
        course_name: resource.course_name,
        date: `${date.getFullYear()}-${date.getMonth()}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`,
      });
      localStorage.setItem("myLikes", JSON.stringify(list));
    }
  };

  render() {
    return (
      <ConfigProvider
        theme={{
          token: {
            colorPrimary: "#ff6741",
            borderRadius: "10px",
          },
        }}
      >
        <section id="explore" className="explore">
          <div className="height100"></div>
          <h2>Explore</h2>
          <div className="height30"></div>
          <center>
            <div className="explore_top_bar">
              <Radio.Group
                defaultValue={this.state.SearchType}
                buttonStyle="solid"
                onChange={this.handleTypeChange}
                value={this.state.SearchType}
              >
                <Radio.Button value="course" defaultChecked>
                  课程
                </Radio.Button>
                <Radio.Button value="tech">技术</Radio.Button>
              </Radio.Group>
              <Button
                type="primary"
                shape="circle"
                icon={<QuestionOutlined style={{ fontSize: "14px" }} />}
                onClick={this.showDrawer}
              ></Button>
            </div>

            <Drawer
              title="技术列表"
              width={520}
              closable={false}
              onClose={this.onClose}
              open={this.state.open}
            >
              <List
                bordered
                dataSource={this.state.AllTechList}
                renderItem={(item) => (
                  <List.Item>
                    <>
                      <div>
                        {/* <Button
                          type="primary"
                          size="small"
                          shape="circle"
                          icon={<PlusOutlined style={{ fontSize: "10px" }} />}
                          onClick={this.showChildrenDrawer}
                        ></Button> */}
                        <p>{item.tech_name}</p>
                      </div>
                      <div className="tech_list_item">
                        <Button
                          type="primary"
                          size="small"
                          shape="circle"
                          icon={<SearchOutlined style={{ fontSize: "10px" }} />}
                          onClick={() => this.chooseTech(item.tech_name)}
                        ></Button>
                        {/* 感觉有点重复？先删除该功能（从右边的所有技术列表中选择课程会出现课程列表，与上面的按钮功能完全一致） */}
                        {/* <Button
                          type="primary"
                          size="small"
                          shape="circle"
                          icon={<RightOutlined style={{ fontSize: "10px" }} />}
                          onClick={()=>this.showChildrenDrawer(item.tech_name)}
                        ></Button> */}
                      </div>
                    </>
                  </List.Item>
                )}
              />

              <Drawer
                title="课程列表"
                width={320}
                closable={false}
                onClose={this.onChildrenDrawerClose}
                open={this.state.childrenDrawer}
              >
                <List
                  bordered
                  dataSource={this.state.CourseList}
                  renderItem={(item) => (
                    <List.Item>
                      <>
                        <p>{item.name}</p>
                        <div className="course_list_item">
                          <Button
                            type="primary"
                            size="small"
                            shape="circle"
                            icon={
                              <SearchOutlined style={{ fontSize: "10px" }} />
                            }
                            onClick={(e) => this.chooseCourse(item.name)}
                          ></Button>
                        </div>
                      </>
                    </List.Item>
                  )}
                />
              </Drawer>
            </Drawer>

            <div className="height30"></div>

            <div className="search-box">
              <input
                className="search-txt"
                type="text"
                name=""
                placeholder="Type to search..."
                onChange={this.handleContentChange}
                value={this.state.SearchContent}
              />
              <a
                className="search-btn"
                onClick={(e) =>
                  this.SearchResources(
                    this.state.SearchType,
                    this.state.SearchContent,
                    this.state.SearchPage,
                    this.state.TechType,
                    this.state.ResourceType
                  )
                }
              >
                <i className="fa-sharp fa-solid fa-magnifying-glass"></i>
              </a>
            </div>
            <div className="height50"></div>
            <div className="search_result_container">
              <div className="search_side_bar">
                <Collapse
                  bordered={false}
                  defaultActiveKey={["1"]}
                  expandIcon={({ isActive }) => (
                    <CaretRightOutlined
                      rotate={isActive ? 90 : 0}
                      style={{ color: "#D9D9D9" }}
                    />
                  )}
                  className="site-collapse-custom-collapse"
                >
                  <Panel
                    header="技术类型"
                    key="1"
                    className="site-collapse-custom-panel"
                  >
                    <Checkbox.Group
                      style={{
                        width: "100%",
                      }}
                      onChange={this.handleTechChange}
                      defaultValue={TechList.map((item) => {
                        return item.name;
                      })}
                    >
                      <Row>{this.TechListCol}</Row>
                    </Checkbox.Group>
                  </Panel>
                  <Panel
                    header="资源类型"
                    key="2"
                    className="site-collapse-custom-panel"
                  >
                    <Checkbox.Group
                      style={{
                        width: "100%",
                      }}
                      onChange={this.handleResourceChange}
                      defaultValue={[
                        "网课",
                        "文档",
                        "仓库",
                        "实用工具",
                        "博客",
                      ]}
                    >
                      <Row>
                        <Col span={12} align="start">
                          <Checkbox value="网课">
                            <p>
                              <font size="2">网课</font>
                            </p>
                          </Checkbox>
                        </Col>
                        <Col span={12} align="start">
                          <Checkbox value="文档">
                            <p>
                              <font size="2">文档</font>
                            </p>
                          </Checkbox>
                        </Col>
                        <Col span={12} align="start">
                          <Checkbox value="仓库">
                            <p>
                              <font size="2">仓库</font>
                            </p>
                          </Checkbox>
                        </Col>
                        <Col span={12} align="start">
                          <Checkbox value="实用工具">
                            <p>
                              <font size="2">实用工具</font>
                            </p>
                          </Checkbox>
                        </Col>
                        <Col span={12} align="start">
                          <Checkbox value="博客">
                            <p>
                              <font size="2">博客</font>
                            </p>
                          </Checkbox>
                        </Col>
                      </Row>
                    </Checkbox.Group>
                  </Panel>
                </Collapse>
              </div>
              <div className="results_container">
                <List
                  bordered
                  dataSource={[...this.state.ResourceData]}
                  footer={<div className="footer" style={{ margin: "70px" }} />}
                  renderItem={(item) => (
                    <List.Item>
                      <SearchResults
                        item={item}
                        course_url={item.course_url}
                        add={this.addToFavorite}
                      />
                    </List.Item>
                  )}
                  pagination={{
                    onChange: () => {},
                    pageSize: 5,
                  }}
                />

                {/* <center>
                  <Pagination
                    defaultCurrent={1}
                    onChange={this.handlePageChange}
                    pageSize={5}
                  />
                </center> */}
              </div>
            </div>
          </center>
          <div className="height100"></div>
        </section>
      </ConfigProvider>
    );
  }
}

export default Explore;
